import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import storage from 'store'
import { RouteRecordRaw } from 'vue-router';

const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
    NProgress.start()
    if (storage.get("token")) {
        if (to.path === '/login') {
            next({ path: '/layout' })
        } else {
            const state = store.state as any;
            if (state.user.roles.length === 0) {
                const res = await store.dispatch('GetInfo')// 拉取用户信息
                console.log(res);
                let menus = res.menus;
                let username = res.username;
                store.dispatch('permission/GenerateRoutes', { menus, username }) // 生成可访问的路由表
                // 动态添加可访问路由表
                state.permission.asyncRoutes.forEach((route: RouteRecordRaw) => {
                    router.addRoute(route); // 为每个路由单独调用addRoute
                });
                next()
            } else {
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login')
        }
    }
})
router.afterEach(() => {
    NProgress.done() // 结束Progress
})
